package kk.web.servlet;

import kk.domain.Manager;
import kk.service.ManagerService;
import kk.service.impl.ManagerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("UTF-8");
        //接受验证码
        String verifycode = request.getParameter("verifycode");//验证码
        //获取session中的验证码
        HttpSession session = request.getSession();
        String checkcode_server = (String)session.getAttribute("CHECKCODE_SERVER");
        //删除session中的验证码，防止验证码二次使用
        session.removeAttribute("CHECKCODE_SERVER");
        //校验验证码
        if(checkcode_server==null || !checkcode_server.equalsIgnoreCase(verifycode)){
            //验证码输入错误，跳转回login.jsp
            request.setAttribute("login_msg","验证码有误！");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {
            //验证码输入正确,获取参数,封装对象
            Manager manager=new Manager();
            Map<String, String[]> parameterMap = request.getParameterMap();
            try {
                BeanUtils.populate(manager,parameterMap);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            //获取管理员账号和密码
            String name=manager.getManager_name();
            String password = manager.getManager_password();
            //调用service方法
            ManagerService managerService=new ManagerServiceImpl();
            Manager loginManager = managerService.login(name, password);
            if (loginManager!=null){
                //登录成功
                //将管理员存入session,并重定向页面到index.jsp
                session.setAttribute("manager",loginManager);
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }else {
                //登录失败
                //在reques域中存入信息并跳转页面
                request.setAttribute("login_msg","用户名或密码输入错误！");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
